<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @reset="handleReset" @submit="handleSubmit">
      <template #anchorSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          :is-date-disabled="disablePreviousDate"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
    </BasicForm>

    <BasicTable
      ref="actionRef"
      :actionColumn="actionColumn"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      :scroll-x="2048"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="禁用">
      <n-form
        ref="formRef"
        :label-width="80"
        :model="formValue"
        :rules="rules"
        class="py-4"
        label-placement="left"
      >
        <n-form-item label="用户状态" path="userStatus">
          <n-switch
            v-model:value="formValue.userStatus"
            :rail-style="railStyle"
            checked-value="able"
            size="large"
            unchecked-value="disable"
            @update:value="userStatusSwitch"
          >
            <template #checked> 正常</template>
            <template #unchecked> 禁用</template>
          </n-switch>
        </n-form-item>

        <n-form-item label="IP" path="ipStatus">
          <n-switch
            v-model:value="formValue.ipStatus"
            :rail-style="railStyle"
            checked-value="able"
            size="large"
            unchecked-value="disable"
            @update:value="ipStatusSwitch"
          >
            <template #checked> 正常</template>
            <template #unchecked> 禁用</template>
          </n-switch>
        </n-form-item>

        <n-form-item label="设备" path="deviceStatus">
          <n-switch
            v-model:value="formValue.deviceStatus"
            :rail-style="railStyle"
            checked-value="able"
            size="large"
            unchecked-value="disable"
            @update:value="deviceStatusSwitch"
          >
            <template #checked> 正常</template>
            <template #unchecked> 禁用</template>
          </n-switch>
        </n-form-item>

        <n-form-item label="主播红包" path="isGrantRed">
          <n-switch
            v-model:value="formValue.isGrantRed"
            :rail-style="railStyle"
            checked-value="able"
            size="large"
            unchecked-value="disable"
            @update:value="isGrantRedStatusSwitch"
          >
            <template #checked> 正常</template>
            <template #unchecked> 禁用</template>
          </n-switch>
        </n-form-item>
      </n-form>

      <!-- <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template> -->
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import { getPlayerPageList, modifyStatus, StatChange } from '@/api/player/playerManage';
  import { formatToDate } from '@/utils/dateUtil';

  const schemas: FormSchema[] = [
    {
      field: 'userId',
      component: 'NInput',
      label: '玩家ID',
      componentProps: {
        placeholder: '玩家ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'name',
      component: 'NInput',
      label: '姓名',
      componentProps: {
        placeholder: '姓名',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'phone',
      component: 'NInput',
      label: '手机号',
      componentProps: {
        placeholder: '手机号',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'roleId',
      component: 'NInput',
      label: '角色ID',
      componentProps: {
        placeholder: '角色ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'idCard',
      component: 'NInput',
      label: '身份证',
      componentProps: {
        placeholder: '身份证',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'timeRange',
      label: '日期',
      componentProps: {
        placeholder: '日期',
      },
      slot: 'anchorSelect',
    },
  ];

  const formValue = reactive({
    userId: 0,
    userStatus: '',
    ipStatus: '',
    deviceStatus: '',
    isGrantRed: '',
    ip: '',
    deviceId: '',
  });

  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const dialog = useDialog();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formParams = reactive({
    userId: 0,
  });

  const params = ref({
    userId: 0,
  });

  const railStyle = ({ focused, checked }: { focused: boolean; checked: boolean }) => {
    const style: CSSProperties = {};
    if (checked) {
      style.background = '#18a058';
      if (focused) {
        style.boxShadow = '0 0 0 2px #d0305040';
      }
    } else {
      style.background = '#ff0000';
      if (focused) {
        style.boxShadow = '0 0 0 2px #2080f040';
      }
    }
    return style;
  };

  const changestatus = (resultParam) => {
    modifyStatus(resultParam);
    // message.success('修改成功');
    setTimeout(function () {
      showModal.value = false;
      reloadTable();
    }, 1500);
  };

  function userStatusSwitch(value) {
    const resultParam: StatChange = {
      type: 3,
      status: value,
      userId: formValue.userId,
    };
    if (value == 'disable') {
      dialog.warning({
        title: '提示',
        content: '被禁用后该玩家将无法正常使用！是否继续操作？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          changestatus(resultParam);
          formValue.userStatus = 'disable';
        },
        onNegativeClick: () => {
          formValue.userStatus = 'able';
          return;
        },
      });
    } else {
      changestatus(resultParam);
      formValue.userStatus = 'able';
    }
  }

  function deviceStatusSwitch(value) {
    const resultParam: StatChange = {
      type: 2,
      status: value,
      userId: formValue.userId,
    };
    if (value == 'disable') {
      dialog.warning({
        title: '提示',
        content: '被禁用后该玩家将无法正常使用！是否继续操作？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          changestatus(resultParam);
          formValue.deviceStatus = 'disable';
        },
        onNegativeClick: () => {
          formValue.deviceStatus = 'able';
          return;
        },
      });
    } else {
      changestatus(resultParam);
      formValue.deviceStatus = 'able';
    }
  }

  function ipStatusSwitch(value) {
    const resultParam: StatChange = {
      type: 1,
      status: value,
      userId: formValue.userId,
    };
    if (value == 'disable') {
      dialog.warning({
        title: '提示',
        content: '被禁用后该玩家将无法正常使用！是否继续操作？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          changestatus(resultParam);
          formValue.ipStatus = 'disable';
        },
        onNegativeClick: () => {
          formValue.ipStatus = 'able';
          return;
        },
      });
    } else {
      changestatus(resultParam);
      formValue.ipStatus = 'able';
    }
  }

  function isGrantRedStatusSwitch(value) {
    const resultParam: StatChange = {
      type: 4,
      status: value,
      userId: formValue.userId,
    };
    if (value == 'disable') {
      dialog.warning({
        title: '提示',
        content: '被禁用后该玩家将无法正常使用！是否继续操作？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          changestatus(resultParam);
          formValue.isGrantRed = 'disable';
        },
        onNegativeClick: () => {
          formValue.isGrantRed = 'able';
          return;
        },
      });
    } else {
      changestatus(resultParam);
      formValue.isGrantRed = 'able';
    }
  }

  const actionColumn = reactive({
    width: 100,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '禁用',
            onClick: handleDetail.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  function addTable() {
    showModal.value = true;
  }

  const loadDataTable = async (res) => {
    if (!formParams.userId) {
      formParams.userId = 0;
    } else {
      formParams.userId = parseInt(formParams.userId);
    }
    const param = { ...formParams, ...res };
    console.log(param);
    delete param.makeDate;
    return await getPlayerPageList(param);
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm() {}

  function handleDetail(record: Recordable) {
    console.log('点击了编辑', record);
    // router.push({name: 'basic-info', params: {id: record.userId}});
    // dialog.info({
    //   title: '提示',
    //   content: `功能未开发`,
    //   positiveText: '确定',
    //   negativeText: '取消',
    //   onPositiveClick: () => {

    //   },
    //   onNegativeClick: () => {

    //   },
    // });
    formValue.userId = record.userId;
    formValue.deviceStatus = record.deviceStatus;
    formValue.isGrantRed = record.isGrantRed;
    formValue.ipStatus = record.ipStatus;
    formValue.userStatus = record.userStatus;
    formValue.ip = record.ip;
    formValue.deviceId = record.deviceId;

    // formValue = Object.assign(unref(formValue), {
    //   deviceId:'正常',
    //   isGrantRed:record.isGrantRed,
    //   devicipeId:record.ip,
    //   userStatus:record.userStatus,

    // });

    showModal.value = true;
  }

  function handleSubmit(values: Recordable) {
    console.log('submit', values);
    let tempParams = unref(formParams);
    tempParams = Object.assign(tempParams, values);
    if (values.makeDate) {
      let [startTime, endTime]: [number, number] = values.makeDate;
      let startTimeS = formatToDate(new Date(startTime));
      let endTimeS = formatToDate(new Date(endTime));
      tempParams = Object.assign(tempParams, { startTime: startTimeS, endTime: endTimeS });
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  onMounted(async () => {
    // registerHandler(ItemTableSwitchActions);
    // const chanList = await getChanList();
    // registChanArray.value = chanList.map((chan) => {
    //   return {
    //     label: chan.chanName,
    //     value: chan.chanId
    //   }
    // });
  });
</script>

<style lang="less" scoped></style>
